package com.itcv.spring.oauth.demo;

import com.itcv.spring.oauth.demo.entity.UserRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.oauth2.OAuth2ClientProperties;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * @author : Windy
 * @version :1.0
 * @since : 2020/12/9 16:44
 */
@RestController
@RequestMapping("/")
public class LoginController {

    @Autowired
    private OAuth2ClientProperties oauth2ClientProperties;
    @Autowired
    private TokenEndpoint tokenEndpoint;

    @PostMapping("/login/admin")
    public OAuth2AccessToken adminLogin(@RequestBody UserRequest request) throws HttpRequestMethodNotSupportedException {
        //创建客户端信息,客户端信息可以写死进行处理，因为Oauth2密码模式，客户端双信息必须存在，所以伪装一个
        //如果不想这么用，需要重写比较多的代码
        User  clientUser= new User(oauth2ClientProperties.getClientId(),oauth2ClientProperties.getClientSecret(), new ArrayList<>());
        //生成已经认证的client
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(clientUser,null, new ArrayList<>());
        Map<String, String> parameters = new HashMap<String, String>();
        //封装成一个UserPassword方式的参数体，放入手机号
        parameters.put("username", request.getPhone());
        //放入验证码
        parameters.put("password", request.getVcode());
        //授权模式为：密码模式
        parameters.put("grant_type", "password");
        //调用自带的获取token方法。
        OAuth2AccessToken oAuth2AccessToken = tokenEndpoint.postAccessToken(token, parameters).getBody();
        return oAuth2AccessToken;
    }



}
